package pers.xiaoliang.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @version v1.0
 * @description: 使用Semaphore信号量 (使用多个许可)
 * @author: xiaoliang.liu
 * @date: 2018/7/28 21:31
 */
@Slf4j
public class SemaphoreExample2 {

    private static final int threadCount = 20;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        // 设置允许的并发数(每次最大执行的线程数, 如果设置为1则程序运行则和单线程一样)
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;

            executorService.execute(() -> {
                try {
                    // 在要控制并发的代码前调用qcuire()方法, 一次获取3个许可 这样类似单线程了
                    semaphore.acquire(3);
                    test(threadNum);
                    // 在要控制并发的代码后调用release()方法, 一次释放3个许可
                    semaphore.release(3);
                } catch (Exception e) {
                    log.info("{}", e);
                }
            });
        }


        // 等待10毫秒，后继续执行代码
        log.info("finish");
        executorService.shutdown();
    }


    public static void test(int threadNum) throws InterruptedException {
        Thread.sleep(1000);
        log.info("{}", threadNum);
        Thread.sleep(1000);
    }
}
